﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace CZ.PAEZ.SaleManager.FormPlugIns
{
    [Description("发票池录入")]
    [HotUpdate]
    public class InvoicePoolInDyForm : AbstractDynamicFormPlugIn
    {

        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            switch (e.Key.ToUpperInvariant())
            {
                case "FGENEINV": // FGeneInv 生成发票
                    Act_BC_GeneInvoiceNumbers();
                    break;
            }
        }

        private void Act_BC_GeneInvoiceNumbers()
        {
            string FInvoiceType =  this.Model.GetValue("FInvoiceType")?.ToString();
            string FInvoiceLot =  this.Model.GetValue("FInvoiceLot")?.ToString();
            string FBeginNo =  this.Model.GetValue("FBeginNo")?.ToString();
            string FEndNo =  this.Model.GetValue("FEndNo")?.ToString();
            string FTaxDiskNo =  this.Model.GetValue("FTaxDiskNo")?.ToString();

            if (FInvoiceType == null) this.View.ShowErrMessage("发票类型不能为空值！");
            if (FInvoiceLot == null) this.View.ShowErrMessage("发票批次不能为空值！");
            else if (FInvoiceLot.Length != 10 && FInvoiceLot.Length != 12) this.View.ShowErrMessage($"发票批次长度{FInvoiceLot.Length}不符合要求！");
            if (FBeginNo == null) this.View.ShowErrMessage("首张发票号不能为空值！");
            else if(FBeginNo.Length != 8) this.View.ShowErrMessage("首张发票号长度需要为8位！");
            if (FEndNo == null) this.View.ShowErrMessage("尾张发票号不能为空值！");
            else if (FEndNo.Length != 8) this.View.ShowErrMessage("尾张发票号长度需要为8位！");

            long FBeginNoLong, FEndNoLong;
            try
            {
                FBeginNoLong = Convert.ToInt64(FBeginNo);
                FEndNoLong = Convert.ToInt64(FEndNo);
            }
            catch(Exception)
            {
                this.View.ShowErrMessage("发票号解析出错，请确定输入的首尾发票号内容是否有误！");
                return;
            }
            
            // 检查发票池中是否与输入发票段冲突
            string sql = string.Format(@"select FNumber from PAEZ_BD_InvoicePool 
where convert(bigint, FNumber) between {0} and {1}
and FInvoiceType='{2}' and FInvoiceLot='{3}'", FBeginNoLong, FEndNoLong, FInvoiceType, FInvoiceLot);
            var numbers = DBUtils.ExecuteDynamicObject(Context, sql);
            if(numbers.Count > 0)
            {
                var list = numbers.Select(i => i["FNumber"].ToString()).ToArray();
                this.View.ShowErrMessage($"可能重复的发票号如下：\n{string.Join(",", list)}", "该批次下的发票号段与发票池中存在的发票号重复，请检查输入是否有误！");
                return;
            }
            // 生成发票池单据
            var meta = ServiceHelper.GetService<IMetaDataService>().Load(Context, "PAEZ_BD_InvoicePool") as FormMetadata;
            var models = new List<DynamicObject>();
            int count = (int)(FEndNoLong - FBeginNoLong + 1);
            this.Model.DeleteEntryData("FEntity");
            this.Model.BatchCreateNewEntryRow("FEntity", count);
            for(int i = 0; i < count; i++)
            {
                string invoice = (FBeginNoLong + i).ToString().PadLeft(8, '0');
                this.Model.SetValue("FINumber", invoice, i);
                var model = new DynamicObject(meta.BusinessInfo.GetDynamicObjectType());
                model["FTaxDiskNo1"] = FTaxDiskNo;
                model["FInvoiceType"] = FInvoiceType;
                model["FInvoiceLot"] = FInvoiceLot;
                model["FNumber"] = invoice;
                model["FIsUsed"] = 0;
                models.Add(model);
            }
            this.View.UpdateView("FEntity");
            var saveSrv = ServiceHelper.GetService<ISaveService>();
            var result = saveSrv.Save(Context, meta.BusinessInfo, models.ToArray());

            this.View.ShowMessage($"发票池成功生成了{result.SuccessDataEnity.Count()}张发票号。");
        }
    }
}
